<?php

namespace app\admin\controller;

use think\facade\App;
use think\facade\Cache;

class Configs extends AdminBase
{
    protected function initialize()
    {
        parent::initialize();
        $this->m = new \app\admin\model\Configs();   //别名：避免与控制名冲突
    }

    public function index()
    {
        $data=$this->m->select();
        $send=[];
        foreach ($data as $d){
            $send[$d['type']][$d['key']]=$d['value'];//格式化数据
        }
        return view('index',$send);
    }

    public function edit()
    {
        if($this->request->isPost()){
            $data=$this->request->post();
            $type=$data['type'];
            unset($data['type']);
            foreach ($data as $key=>$value){
                $config=\app\admin\model\Configs::where(['type'=>$type,'key'=>$key])->find();
                if($config){
                    $config->save(['value'=>$value]);
                }
            }
            return xjson('更新成功！');
        }

    }
    public function clean_cache(){
        \think\facade\Cache::delete('myConfig');
        return xjson('清除缓存成功！');
    }
        // 清除缓存
    public function clear()
    {
        $path = App::getRootPath() . 'runtime';
        if ($this->_deleteDir($path)) {
            $result['code']=0;
            $result['msg'] = '清除缓存成功!';
            $result['error'] = 0;
        } else {
            $result['code']=307;
            $result['msg'] = '清除缓存失败!';
            $result['error'] = 1;
        }
        $result['url'] = (string)url('login/index');
        return json($result);
    }
    // 执行删除runtime
    private function _deleteDir($R)
    {
        Cache::clear();
        $handle = opendir($R);
        while (($item = readdir($handle)) !== false) {
            // log目录不可以删除
            if ($item != '.' && $item != '..' && $item != 'log') {
                if (is_dir($R . DIRECTORY_SEPARATOR . $item)) {
                    $this->_deleteDir($R . DIRECTORY_SEPARATOR . $item);
                } else {
                    if ($item != '.gitignore') {
                        if (!unlink($R . DIRECTORY_SEPARATOR . $item)) {
                            return false;
                        }
                    }
                }
            }
        }
        closedir($handle);
        return true;

    }

}
